#include "Money.h"


Money::Money():units(0), curr("USD"){}
Money::Money(long v, string cr):units(v), curr(cr){}
Money::Money(int d, int c, string cr):units(100*d+c), curr(cr){}


int Money::dollars() const
{
	return units/100;
}

int Money::cents()	  const
{
	return units % 100;
}


long Money::get_value() const
{
	return units;
}

void Money::set_value(long nv)
{
	units = nv;
}



ostream& operator << (ostream& ostr, const Money& m)
{
	return ostr << '$' << m.dollars() << '.' << ((m.cents()<10)?"0":"")  << m.cents();  	
}

istream& operator >> (istream& istr, Money& m)
{
	char cs, ds;
	int d, c;
	istr >> cs >> d >>  ds >> c;
	if (!istr) return istr;
	if (cs!='$'||ds!='.')
	{
		istr.clear(ios_base::failbit);
		return istr;
	}
	m.set_value(100*d+c);
	return istr;
}


Money operator + (const Money& a, const Money& b)
{
	return Money(a.get_value() + b.get_value());
}
Money operator - (const Money& a, const Money& b)
{
	return Money(a.get_value() - b.get_value());
}
Money operator * (const Money& a, double m)
{
	double nw = a.get_value()*m;
	long  lnw = long(a.get_value()*m);
	if(nw-lnw >= 0.5)
		return (Money(lnw+1));
	else
		return (Money(lnw));
}
Money operator / (const Money& a, double d)
{
	if (d==0) error ("Divide by zero");
	double nw = a.get_value()/d;
	long  lnw = long(a.get_value()/d);
	if(nw-lnw >= 0.5)
		return (Money(lnw+1));
	else
		return (Money(lnw));
}